package com.memoryangelapplication;

/*
 * 
 * **************Alert Massage Display Event*************
 * Class Includes Functions For
 * 1. Display front end details of an Alert 
 * 2. Capture Alert awaiting time 
 * 3. Capture Event Alert Display time 
 * 4. Schedule next alert 
 * 
 * */
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.memoryangelapplication.global.Event_pass;
import com.memoryangelapplication.model.EventObj;
import com.memoryangelapplication.services.EventAlarm;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.PowerManager;
import android.os.Vibrator;
import android.os.PowerManager.WakeLock;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AlertMessageActivity extends Activity implements
		TextToSpeech.OnInitListener {
	int sendCounter;
	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "memoryangel.db";
	private static final String TAG = null;
	// Master Tables
	private String MEM_USER = "table_user";
	private String MEM_EVENT = "table_events";
	String wtever = "What Ever";
	String event_log_id = "";
	String evtTitle = "";
	String evtDate = "";
	String evtTime = "";
	String evtDes = "";
	String event_time_stamp = "";
	String updateEventId;
	String timeSet = "";
	int hours;
	int minute;
	// Default Settings For Reminders
	String eventremindertime = "";
	String eventremindernumberStr = "";
	String eventwaittime = "";
	Context context;
	ArrayList<EventObj> lst = new ArrayList<EventObj>();
	int delay = 0;
	boolean isFirstTime = true;
	int period = 60000;
	int wait_time;
	int eventwaittimePeriod;
	int event_reminder_time;
	int reminder_number;
	long nextReminderTimeStamp;
	MediaPlayer player;
	public static int counter = 0;
	public static int repeat_counter = 0;
	int eventTTS = 1;
	int eventSoundGap;
	int eventContPlay;
	String EvetFlag = "0000";
	ScheduledThreadPoolExecutor executor;
	ScheduledThreadPoolExecutor executor1;
	Handler handler, main_handelr;
	SoundManager soundManager;
	SoundManager1 soundManager1;
	TextToSpeech talker;
	EditText eventmainid;
	Runnable r1;
	String current_time;
	String newhours = null;
	String newminute;
	String DateSendAct, TimeAct, Tzone;
	long TimeStampValue;
	String eventPackage;
	String eventURL;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Remove title bar
	    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    //Remove notification bar
	    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.event_values);

		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
						| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
						| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
		
		getWindow().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_NEW_TASK);
		
		KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);  
		KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE); 
		lock.disableKeyguard();
		
		
		context = AlertMessageActivity.this;
		PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
		WakeLock wakeLock = powerManager.newWakeLock(
				PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
		wakeLock.acquire();

		Bundle bundle = getIntent().getExtras();
		event_log_id = bundle.getString("event_log_id");
		updateEventId = bundle.getString("event_id");
		evtTitle = bundle.getString("event_title");
		evtDate = bundle.getString("event_date");
		evtTime = bundle.getString("event_time");
		evtDes = bundle.getString("event_description");
		eventremindertime = bundle.getString("event_eventremindertime");
		event_reminder_time = Integer.parseInt(eventremindertime);
		eventremindernumberStr = bundle.getString("event_eventremindernumber");
		reminder_number = Integer.parseInt(eventremindernumberStr);
		eventwaittime = bundle.getString("event_eventwaittime");
		eventwaittimePeriod = Integer.parseInt(eventwaittime);

		wait_time = eventwaittimePeriod * 1000;

		// Time Zone Of the Current Phone
		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
				Locale.getDefault());
		Date currentLocalTime = calendar.getTime();
		DateFormat date = new SimpleDateFormat("Z");
		Tzone = date.format(currentLocalTime);
		Tzone = " " + Tzone;
		String currentTime = getAddDateTimeStringPreCheck();
		String[] CheckDayTime = currentTime.split(" ");
		DateSendAct = CheckDayTime[0];
		TimeAct = CheckDayTime[1];
		getNativeTimeStamp(DateSendAct, TimeAct, Tzone);

		Log.e("wait_time ", "wait_time:" + wait_time);
		Log.e("event_reminder_time ", "event_reminder_time:"
				+ event_reminder_time);
		Log.e("reminder_number ", "reminder_number:" + reminder_number);

		String nxtIcrs = bundle.getString("nxt_incr");

		final int nxtIcr = Integer.parseInt(nxtIcrs);

		// Schedule Events Threads Handling Sounds and Display
		executor = new ScheduledThreadPoolExecutor(1);
		executor1 = new ScheduledThreadPoolExecutor(1);

		talker = new TextToSpeech(this, this);
		main_handelr = new Handler();

		new CountDownTimer(wait_time, 1000) {
			public void onTick(long millisUntilFinished) {
				Log.e("Timmer Started", "Timmer Started");
			}

			// Remove Alertfrom the screen
			// Set Next Alert
			// Update Backend
			public void onFinish() {
				executor.shutdown();
				executor.shutdownNow();
				executor.remove(soundManager);

				executor1.shutdown();
				executor1.shutdownNow();
				executor1.remove(soundManager1);
				eventDetailsUpdate();
				setNextReminder();
				AlertMessageActivity.this.finish();
			}
		}.start();
		// for viberating and using media player
		try {
			Vibrator myVib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
			myVib.vibrate(3000);

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		// How many times alert need to be display
		if (reminder_number == 0) {
			reminder_number = 3;

		}
		// Reminder Delay
		if (event_reminder_time == 0) {
			event_reminder_time = 60;

		}
		// Display Reminder
		if (wait_time == 0) {
			// if 0 then default will be 5
			wait_time = 45 * 1000;
		}
		eventTTS = 1;
		eventContPlay = 1;
		eventSoundGap = 1000;

		if (eventSoundGap == 0) {
			eventSoundGap = 5;
		}
		// Media Player handling events
		if (eventTTS == 1 && eventContPlay == 1) {
			AlertMessageActivity.counter++;
			soundManager = new SoundManager();
			executor.scheduleAtFixedRate(soundManager, 0, 3000,
					TimeUnit.MILLISECONDS);

		} else if (eventTTS == 1 && eventContPlay == 0) {
			if (AlertMessageActivity.counter == 0) {

				AlertMessageActivity.counter++;
				setVolumeControlStream(AudioManager.STREAM_MUSIC);
				// our file here is in fact called "soundfile.mp3";
				MediaPlayer player = MediaPlayer.create(
						AlertMessageActivity.this, R.raw.alarm);
				// we start playing the file!
				player.start();

				player.setOnCompletionListener(new OnCompletionListener() {

					@Override
					public void onCompletion(MediaPlayer mp) {
						mp.stop();
						mp.release();
						Handler handler = new Handler();
						final Runnable r = new Runnable() {
							public void run() {
								String text = evtDes;
								talker.speak(text, TextToSpeech.QUEUE_FLUSH,
										null);
							}
						};
						handler.postDelayed(r, 3000);
					}
				});
			}

		} else if (eventTTS == 0 && eventContPlay == 1) {
			soundManager1 = new SoundManager1();
			executor1.scheduleAtFixedRate(soundManager1, 0, 3000,
					TimeUnit.MILLISECONDS);
		} else if (eventTTS == 0 && eventContPlay == 0) {

			if (AlertMessageActivity.counter == 0) {

				AlertMessageActivity.counter++;

				setVolumeControlStream(AudioManager.STREAM_MUSIC);
				// our file here is in fact called "soundfile.mp3";

				MediaPlayer player = MediaPlayer.create(
						AlertMessageActivity.this, R.raw.alarm);
				// we start playing the file!
				player.start();
				player.setOnCompletionListener(new OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
						mp.stop();
						mp.release();
					}

				});

			}

		}

		// Front end display events details
		RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.alert_layout);
		rlayout.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				lst = Event_pass.getData();
				if (lst != null && lst.size() > nxtIcr) {

					EventObj mth = (EventObj) lst.get(nxtIcr);
					if (lst != null) {
						Intent i2 = new Intent(getApplicationContext(),
								AlertMessageActivity.class);

						event_log_id = mth.getEvent_event_log_id();
						Log.v("LOG -", "ALAM ID : " + updateEventId);
						i2.putExtra("event_id", mth.getEvent_time_stamp());
						i2.putExtra("event_title", mth.getEvent_title());
						i2.putExtra("event_date", mth.getEvent_date());
						i2.putExtra("event_time", mth.getEvent_time());
						i2.putExtra("event_description",
								mth.getEvent_description());
						i2.putExtra("eventremindertime",
								mth.getEvent_eventremindertime());
						i2.putExtra("eventremindernumber",
								mth.getEvent_eventremindernumber());
						i2.putExtra("eventwaittime",
								mth.getEvent_eventwaittime());
						i2.putExtra("nxt_incr", "" + (nxtIcr + 1));
						startActivity(i2);
					}
				} else {

				}

				executor.shutdown();
				executor.shutdownNow();
				executor.remove(soundManager);

				executor1.shutdown();
				executor1.shutdownNow();
				executor1.remove(soundManager1);
				updateState();
				// callSevices();
				return false;

			}
		});
		eventmainid = (EditText) findViewById(R.id.eventmainid);
		TextView EvtDate = (TextView) findViewById(R.id.reminder_date);
		TextView EvtTime = (TextView) findViewById(R.id.reminder_time);
		TextView EvtTitle = (TextView) findViewById(R.id.title);
		TextView EvtDes = (TextView) findViewById(R.id.description);
		eventmainid.setText(event_log_id);
		EvtTitle.setText(evtTitle);
		EvtDate.setText(evtDate);
		EvtTime.setText(evtTime);
		EvtDes.setText(evtDes);

	}

	public long getNativeTimeStamp(String DateSend, String Time, String Tzone) {
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm zzzzz");
		Calendar c = Calendar.getInstance();
		Date d = null;

		try {
			d = ddMMMyyFormat
					.parse(DateSend.trim() + " " + Time.trim() + Tzone);

		} catch (ParseException e) {
			e.printStackTrace();
		}

		c.setTime(d);

		String date_to_string = ddMMMyyFormat
				.format(c.getTimeInMillis() / 1000);
		TimeStampValue = c.getTimeInMillis() / 1000;
		return c.getTimeInMillis() / 1000;
	}

	protected void setNextReminder() {
		Bundle bundle = new Bundle();
		EventAlarm alarm1 = new EventAlarm(context, bundle, event_reminder_time);
	}

	private void eventDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;

		try {
			String query = "SELECT * FROM table_events WHERE event_log_id = 'event_log_id'";
			allrowitemsdes = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		// Don't forget to shutdown!
		if (talker != null) {
			talker.stop();
			talker.shutdown();
		}

	}

	class SoundManager implements Runnable {

		int counter = 0;

		@Override
		public void run() {

			if ((counter % 2) == 0) {

				setVolumeControlStream(AudioManager.STREAM_MUSIC);
				// our file here is in fact called "soundfile.mp3";

				MediaPlayer player = MediaPlayer.create(
						AlertMessageActivity.this, R.raw.alarm);
				// we start playing the file!
				player.start();

				player.setOnCompletionListener(new OnCompletionListener() {

					@Override
					public void onCompletion(MediaPlayer mp) {
						mp.stop();
						mp.release();

					}
				});

			} else if ((counter % 2) != 0) {
				String text = evtDes;
				talker.speak(text, TextToSpeech.QUEUE_FLUSH, null);
			}
			counter++;
		}

	}

	class SoundManager1 implements Runnable {

		@Override
		public void run() {

			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			// our file here is in fact called "soundfile.mp3";

			MediaPlayer player = MediaPlayer.create(AlertMessageActivity.this,
					R.raw.alarm);
			// we start playing the file!
			player.start();

			player.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					mp.stop();
					mp.release();
				}
			});
		}

	}

	protected void updateState() {
		// TODO Auto-generated method stub
		if(event_log_id == null || event_log_id.equals("")){
			event_log_id = eventmainid.getText().toString().trim();
		}
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor checkPreEvents = null;
		try {
			String query = "SELECT event_log_id,event_time_stamp,event_alam_time,event_url,event_package FROM table_events Where event_log_id = '"
					+ event_log_id + "'";
			checkPreEvents = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (checkPreEvents != null) {
			if (checkPreEvents.getCount() > 0) {
				while (checkPreEvents.moveToNext()) {
					ContentValues updateEvets = new ContentValues();
					String updateID = checkPreEvents.getString(0);
					eventURL = checkPreEvents.getString(3);
					eventPackage = checkPreEvents.getString(4);

					updateEvets.put("event_status", "3");
					updateEvets.put("event_active", "1");
					updateEvets.put("event_update_time", getAddDateTimeString()
							.toString());
					mydb.update(MEM_EVENT, updateEvets, "event_log_id ='"
							+ updateID + "'", null);
				}
			}
		}
		checkPreEvents.close();
		mydb.close();
		
		Log.e("REQUEST 1:", "VAL PASS 1 :" +eventURL);
		Log.e("REQUEST 2:", "VAL PASS 2 :" +eventPackage);
		
		if (eventPackage.equals("404") && eventURL.equals("404")) {
			closeExcecutor();
			AlertMessageActivity.this.finish();
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
		} else if (!eventURL.equals("404")) {
			try {
				Log.e("REQUEST :", "Fire URL**********");
				closeExcecutor();
				Intent viewIntent = new Intent("android.intent.action.VIEW",
						Uri.parse(eventURL.trim()));
				viewIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                         | Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(viewIntent);
				AlertMessageActivity.this.finish();
				finish();
				android.os.Process.killProcess(android.os.Process.myPid());
			} catch (Exception e) {

			}
		} else if (!eventPackage.equals("404")) {
			Log.e("REQUEST :", "Fire Package************");
			closeExcecutor();
			Intent i = new Intent(Intent.ACTION_MAIN);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                    | Intent.FLAG_ACTIVITY_NEW_TASK);
			PackageManager managerclock = getPackageManager();
			i = managerclock.getLaunchIntentForPackage(eventPackage.trim());
			i.addCategory(Intent.CATEGORY_LAUNCHER);
			startActivity(i);
			AlertMessageActivity.this.finish();
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
		}
		else{
			closeExcecutor();
			AlertMessageActivity.this.finish();
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
		}
		/*
		 * //Allow To Trigger If Previous Events Excisting Bundle bundle = new
		 * Bundle(); EventAlarm alarm1 = new EventAlarm(this, bundle, 1);
		 */
	}

	private void closeExcecutor() {
		// TODO Auto-generated method stub
		executor.shutdown();
		executor.shutdownNow();
		executor.remove(soundManager);

		executor1.shutdown();
		executor1.shutdownNow();
		executor1.remove(soundManager1);
	}

	protected void eventDetailsUpdate() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor checkPreEventsAckCount = null;

		try {
			String query = "SELECT event_log_id,event_time_stamp,event_alam_time,event_ack_count,eventReminderTime,eventReminderNumber,eventWaitTime,eventTimeStamp FROM table_events Where event_alam_time = '"
					+ updateEventId + "'";
			checkPreEventsAckCount = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (checkPreEventsAckCount != null) {
			if (checkPreEventsAckCount.getCount() > 0) {
				while (checkPreEventsAckCount.moveToNext()) {
					ContentValues updateEvetsCount = new ContentValues();
					String updateID = checkPreEventsAckCount.getString(0);
					String event_alam_time = checkPreEventsAckCount
							.getString(2);
					long event_alam_timecount = Long.parseLong(event_alam_time);

					String updateCounter = checkPreEventsAckCount.getString(3);
					String eventReminderTime = checkPreEventsAckCount
							.getString(4);
					String eventReminderNumber = checkPreEventsAckCount
							.getString(5);
					String eventWaitTime = checkPreEventsAckCount.getString(6);
					String eventCurrentTimeStamp = checkPreEventsAckCount
							.getString(7);

					int eventReminderNumbercount = Integer
							.parseInt(eventReminderNumber);
					// Event Reminder Time = Time 1
					long eventReminderTimecount = Long
							.parseLong(eventReminderTime);
					long eventeventWaitTimecount = Long
							.parseLong(eventWaitTime);
					long eventeventCurrentTimeStamp = Long
							.parseLong(eventCurrentTimeStamp);

					long curCount = Long.parseLong(updateCounter);
					curCount = curCount + 1;

					long newEventCurrentTimeStamp = (eventReminderTimecount + eventeventWaitTimecount)
							* curCount;
					newEventCurrentTimeStamp = newEventCurrentTimeStamp
							+ TimeStampValue;
					String newEventCurrentTimeStampStr = String
							.valueOf(newEventCurrentTimeStamp);

					if (eventReminderNumbercount == curCount) {
						updateEvetsCount.put("event_status", "4");
						updateEvetsCount.put("event_ack_count", curCount);
						updateEvetsCount.put("event_active", "1");
						updateEvetsCount.put("event_alam_time",
								newEventCurrentTimeStampStr);

						mydb.update(MEM_EVENT, updateEvetsCount,
								"event_log_id ='" + updateID + "'", null);
					} else {
						nextReminderTimeStamp = newEventCurrentTimeStamp;
						newEventCurrentTimeStampStr = String
								.valueOf(nextReminderTimeStamp);
						updateEvetsCount.put("event_ack_count", curCount);
						updateEvetsCount.put("event_status", "9");
						updateEvetsCount.put("event_alam_time",
								newEventCurrentTimeStampStr);
						mydb.update(MEM_EVENT, updateEvetsCount,
								"event_log_id ='" + updateID + "'", null);
					}

				}
			}
		}
		checkPreEventsAckCount.close();
		mydb.close();

	}

	@Override
	public void onInit(int status) {
		// TODO Auto-generated method stub

	}

	// Used to convert 24hr format to 12hr format with AM/PM values
	private void updateTime(int hours, int mins) {

		if (hours > 12) {
			hours -= 12;
			timeSet = "PM";
		} else if (hours == 0) {
			hours += 12;
			timeSet = "AM";
		} else if (hours == 12)
			timeSet = "PM";
		else
			timeSet = "AM";

		String minutes = "";
		if (mins < 10)
			minutes = "0" + mins;
		else
			minutes = String.valueOf(mins);

		// Append in a StringBuilder
		String aTime = new StringBuilder().append(hours).append(':')
				.append(minutes).append(" ").append(timeSet).toString();
		// output.setText(aTime);
	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	private String getAddDateTimeStringPreCheck() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}
}
